<template>
  <div class="project-info">
    <SettingHeader title="项目基本信息">
      <template #operate>
        <el-button v-show="!isEdit && projectNoFinishLimit" @click="editProjectInfo">
          <SvgIcon class="svg-icon" name="project-edit"></SvgIcon>
          编辑
        </el-button>
        <el-button v-show="isEdit" type="primary" @click="submitFrom" :loading="saveLoading">保存</el-button>
        <el-button v-show="isEdit" @click="cancelEdit">取消编辑</el-button>
        <el-button v-if="projectNoFinishLimit" :loading="saveLoading" @click="projectFiled">
          <SvgIcon class="svg-icon" name="project-finish"></SvgIcon>
          归档
        </el-button>
        <el-button v-if="projectNoFinishLimit" @click="deleteProjectClick" :loading="deleteLoading">
          <SvgIcon class="svg-icon" name="project-delete"></SvgIcon>
          删除
        </el-button>
      </template>
    </SettingHeader>
    <!-- <el-divider /> -->
    <div class="project-info-center">
      <div class="project-info-content">
        <div class="project-info-config">
          <div class="project-header">
            <div class="project-header-icon"></div>
            <div class="project-header-title">基本信息</div>
          </div>
          <el-form
            :model="projectForm"
            ref="formRef"
            label-width="130px"
            :rules="formRules"
            :hide-required-asterisk="!isEdit">
            <el-row :gutter="10">
              <el-col :span="11">
                <el-form-item label="项目名称：" prop="projectName" :style="formStyle">
                  <el-input
                    v-if="isEdit"
                    v-model.trim="projectForm.projectName"
                    placeholder="请输入项目名称"
                    maxlength="25"></el-input>
                  <div v-else class="form-value">{{ projectForm.projectName }}</div>
                </el-form-item>
              </el-col>
              <el-col :span="11">
                <el-form-item label="项目编码：" :style="formStyle">
                  <div class="form-value">{{ projectForm.projectCode }}</div>
                </el-form-item>
              </el-col>
            </el-row>

            <el-row :gutter="10">
              <el-col :span="11">
                <el-form-item label="项目集：" :style="formStyle">
                  <el-tree-select
                    v-if="isEdit"
                    v-model="projectForm.parentId"
                    :data="projectTreeData"
                    :props="treeProps"
                    clearable
                    check-strictly
                    :render-after-expand="true"
                    :check-on-click-node="true"
                    style="width: 100%"
                    placeholder="请选择" />
                  <div v-else class="form-value">{{ infoForm.projectGroup?.projectName }}</div>
                </el-form-item>
              </el-col>
              <el-col :span="11">
                <el-form-item label="归属部门：" prop="deptId" :style="formStyle">
                  <el-tree-select
                    v-if="isEdit"
                    v-model="projectForm.deptId"
                    :data="deptList"
                    :props="deptProps"
                    clearable
                    check-strictly
                    :render-after-expand="true"
                    :check-on-click-node="true"
                    style="width: 100%"
                    placeholder="请选择" />
                  <div v-else class="form-value">{{ infoForm.dept?.label }}</div>
                </el-form-item>
              </el-col>
            </el-row>

            <el-row :gutter="10">
              <el-col :span="11">
                <el-form-item label="项目经理：" prop="projectManager" :style="formStyle">
                  <el-select
                    v-if="isEdit"
                    v-model="projectForm.projectManager"
                    placeholder="请选择"
                    style="width: 100%"
                    clearable
                    filterable>
                    <el-option v-for="item in userList" :key="item.value" :label="item.nickName" :value="item.userId" />
                  </el-select>
                  <div v-else class="form-value">{{ infoForm.user?.nickName }}</div>
                </el-form-item>
              </el-col>
              <el-col :span="11">
                <el-form-item label="项目类型：" prop="projectType" :style="formStyle">
                  <el-select
                    v-if="isEdit"
                    style="width: 100%"
                    v-model="projectForm.projectType"
                    placeholder="请选择项目类型"
                    clearable>
                    <el-option
                      v-for="(item, index) in dict.dictMap['task_project_type']"
                      :key="index"
                      :label="item.dictLabel"
                      :value="Number(item.dictValue)"></el-option>
                  </el-select>
                  <div v-else class="form-value">
                    {{ dict.translate('task_project_type', projectForm.projectType) }}
                  </div>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="10">
              <el-col :span="11">
                <el-form-item label="项目分类：" prop="projectClass" :style="formStyle">
                  <el-select
                    v-if="isEdit"
                    style="width: 100%"
                    v-model="projectForm.projectClass"
                    placeholder="请选择项目分类"
                    clearable>
                    <el-option
                      v-for="(item, index) in dict.dictMap['task_project_class']"
                      :key="index"
                      :label="item.dictLabel"
                      :value="Number(item.dictValue)"></el-option>
                  </el-select>
                  <div v-else class="form-value">
                    {{ dict.translate('task_project_class', projectForm.projectClass) }}
                  </div>
                </el-form-item>
              </el-col>
              <el-col :span="11">
                <el-form-item label="任务编辑模式：" prop="isCreate" :style="formStyle">
                  <el-select
                    v-if="isEdit"
                    style="width: 100%"
                    v-model="projectForm.isCreate"
                    placeholder="请选择编辑模式"
                    clearable>
                    <el-option
                      v-for="(item, index) in dict.dictMap['task_edit_mode']"
                      :key="index"
                      :label="item.dictLabel"
                      :value="Number(item.dictValue)"></el-option>
                  </el-select>
                  <div v-else class="form-value">{{ dict.translate('task_edit_mode', projectForm.isCreate) }}</div>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="10">
              <el-col :span="11">
                <el-form-item label="计划时间：" prop="planEnd" :style="formStyle">
                  <!--                     value-format="YYYY-MM-DD HH:mm:ss" -->
                  <el-date-picker
                    v-if="isEdit"
                    :model-value="[projectForm.planBegin, projectForm.planEnd]"
                    type="daterange"
                    format="YYYY-MM-DD"
                    :unlink-panels="true"
                    range-separator="-"
                    start-placeholder="开始时间"
                    end-placeholder="结束时间"
                    :default-time="defaultTime"
                    @update:modelValue="planDateChange" />
                  <div v-else class="form-value">
                    {{ dayjs(projectForm.planBegin).format('YYYY-MM-DD') }} 至
                    {{ dayjs(projectForm.planEnd).format('YYYY-MM-DD') }}
                  </div>
                </el-form-item>
              </el-col>
              <el-col :span="13">
                <el-form-item label="项目标签：" prop="projectTag" :style="formStyle">
                  <el-tag
                    v-for="tag in projectForm.tagList"
                    :key="tag"
                    class="mb-4"
                    :disable-transitions="false"
                    :closable="isEdit"
                    @close="deleteTag(tag)">
                    {{ tag.tagName }}
                  </el-tag>
                  <div v-if="inputVisible">
                    <el-input
                      v-model="tagValue"
                      maxlength="15"
                      show-word-limit
                      class="tag-input"
                      placeholder="请输入标签" />
                    <el-button type="primary" circle @click="tagConfirm" size="small">
                      <SvgIcon class="svg-icon-btn" name="project-confirm"></SvgIcon>
                    </el-button>
                    <el-button type="info" circle @click="tagCancel" size="small">
                      <SvgIcon class="svg-icon-btn" name="project-cancel"></SvgIcon>
                    </el-button>
                  </div>
                  <el-button v-else-if="isEdit" class="button-new-tag ml-1" size="small" @click="showInput">
                    +
                  </el-button>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="10">
              <el-col :span="22">
                <el-form-item label="项目描述：" :style="formStyle">
                  <Editor
                    v-if="isEdit"
                    ref="editor"
                    :excludeKeys="[
                      'group-video',
                      'emotion',
                      'lineHeight',
                      'insertTable',
                      'divider',
                      'codeBlock',
                      'insertLink',
                      'bgColor',
                      'fontFamily',
                      'undo',
                      'redo',
                      'blockquote',
                      'todo',
                      'group-indent',
                      'group-more-style',
                      'fullScreen',
                    ]"
                    :valueHtml="projectRemark"
                    :folderId="projectForm.projectFolderId"
                    :folderName="'项目'"
                    :folderType="'project'"
                    :height="'250px'" />
                  <div v-else class="project-describe">
                    <RichTextViewer :view-html="projectRemark"></RichTextViewer>
                  </div>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </div>
        <el-divider />
        <div class="project-info-stage">
          <div class="project-header">
            <div class="project-header-icon"></div>
            <div class="project-header-title">项目阶段</div>
          </div>
          <div class="project-info-stage-content" v-if="projectForm.tcTaskItemsList?.length">
            <el-steps :active="currentStage" align-center :space="200">
              <el-step v-for="(item, index) in groupList" :key="index">
                <template #title>
                  <span v-if="currentStage === 0" class="step-title-default">{{ item.itemName }}</span>
                  <span v-else-if="index < currentStage">{{ item.itemName }}</span>
                  <span v-else class="step-title-default">{{ item.itemName }}</span>
                </template>
                <template #icon>
                  <div class="step-item step-item-default" v-if="currentStage === 0">
                    <SvgIcon class="svg-icon" name="project-step"></SvgIcon>
                  </div>
                  <div class="step-item step-item-active" v-else-if="index < currentStage">
                    <SvgIcon class="svg-icon" name="project-step-active"></SvgIcon>
                  </div>
                  <div class="step-item step-item-default" v-else>
                    <SvgIcon class="svg-icon" name="project-step"></SvgIcon>
                  </div>
                </template>
                <template #description>
                  <div class="step-description">
                    {{ item.itemBegin ? dayjs(item.itemBegin).format('YYYY-MM-DD') : '未选择' }}
                  </div>
                  <SvgIcon class="svg-icon" name="project-line"></SvgIcon>
                  <div class="step-description">
                    {{ item.itemEnd ? dayjs(item.itemEnd).format('YYYY-MM-DD') : '未选择' }}
                  </div>
                </template>
              </el-step>
            </el-steps>
          </div>
          <el-empty v-else description="暂无阶段" :image-size="50"></el-empty>
        </div>
        <el-divider />
        <div class="project-info-record">
          <div class="project-header">
            <div class="project-header-icon"></div>
            <div class="project-header-title">阶段记录</div>
            <div class="project-header-button">
              <el-button v-if="projectNoFinishLimit" @click="handleAdd(data, node)">
                <SvgIcon name="project-plus" class="project-plus"></SvgIcon>
                添加
              </el-button>
            </div>
          </div>
          <el-form :model="projectForm" ref="tableFormRef" :rules="tableFormRules">
            <el-table
              class="elTable"
              :data="projectForm.tcTaskItemsList"
              style="width: 100%; margin-bottom: 20px"
              row-key="itemId"
              :row-class-name="activeClass"
              default-expand-all
              :tree-props="{ children: 'itemsChildren' }"
              :indent="20">
              <el-table-column label="阶段名称" prop="itemName">
                <template v-slot="scope">
                  <span v-if="!scope.row.editFlag">{{ scope.row.itemName }}</span>
                  <el-form-item
                    v-else
                    :rules="tableFormRules.itemName"
                    :prop="`tcTaskItemsList.${findPosi(projectForm.tcTaskItemsList, scope.row.itemId)}.itemName`">
                    <el-input
                      v-model.trim="scope.row.itemName"
                      maxlength="25"
                      placeholder="请输入阶段名称"
                      style="width: 100%"></el-input>
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column label="开始时间" prop="itemBegin">
                <template v-slot="scope">
                  <span v-if="!scope.row.editFlag">
                    {{ scope.row.itemBegin ? dayjs(scope.row.itemBegin).format('YYYY-MM-DD') : '' }}
                  </span>
                  <el-form-item
                    v-else
                    :rules="tableFormRules.itemBegin"
                    :prop="`tcTaskItemsList.${findPosi(projectForm.tcTaskItemsList, scope.row.itemId)}.itemBegin`">
                    <el-date-picker
                      v-model="scope.row.itemBegin"
                      placeholder="请选择开始时间"
                      format="YYYY-MM-DD"
                      value-format="YYYY-MM-DD HH:mm:ss"
                      style="width: 100%"
                      :disabled-date="
                        (date) =>
                          dayjs(scope.row.itemEnd || '').isBefore(date, 'day') ||
                          dayjs(projectForm?.planEnd).isBefore(date, 'day') ||
                          dayjs(scope.row.parent?.itemEnd || '').isBefore(date, 'day') ||
                          dayjs(projectForm?.planBegin).isAfter(date, 'day') ||
                          dayjs(scope.row.parent?.itemBegin || '').isAfter(date, 'day')
                      "></el-date-picker>
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column label="结束时间" prop="itemEnd">
                <template v-slot="scope">
                  <span v-if="!scope.row.editFlag">
                    {{ scope.row.itemEnd ? dayjs(scope.row.itemEnd).format('YYYY-MM-DD') : '' }}
                  </span>
                  <el-form-item
                    v-else
                    :rules="tableFormRules.itemEnd"
                    :prop="`tcTaskItemsList.${findPosi(projectForm.tcTaskItemsList, scope.row.itemId)}.itemEnd`">
                    <el-date-picker
                      style="width: 100%"
                      v-model="scope.row.itemEnd"
                      placeholder="请选择结束时间"
                      format="YYYY-MM-DD"
                      value-format="YYYY-MM-DD HH:mm:ss"
                      :disabled-date="
                        (date) =>
                          dayjs(scope.row.itemBegin || '').isAfter(date, 'day') ||
                          dayjs(projectForm?.planEnd).isBefore(date, 'day') ||
                          dayjs(scope.row.parent?.itemEnd || '').isBefore(date, 'day') ||
                          dayjs(projectForm?.planBegin).isAfter(date, 'day') ||
                          dayjs(scope.row.parent?.itemBegin || '').isAfter(date, 'day')
                      "></el-date-picker>
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column label="计划人天" prop="planCostDay"></el-table-column>
              <el-table-column label="操作" width="120" class-name="table-ation" fixed="right">
                <!-- <template #header>
                  <el-tooltip class="box-item" effect="dark" content="新增" placement="top-start">
                    <li @click="handleAdd(data, node)">
                      <SvgIcon name="add"></SvgIcon>
                    </li>
                  </el-tooltip>
                </template> -->
                <template v-slot="scope">
                  <span class="table-action">
                    <template v-if="!scope.row.editFlag && projectNoFinishLimit">
                      <li @click="handleAddChildren(scope.row)" v-if="scope.row.parentId === 0">
                        <SvgIcon name="add"></SvgIcon>
                      </li>
                      <li @click="handleEdit(scope.row)">
                        <SvgIcon name="edit"></SvgIcon>
                      </li>
                    </template>
                    <li v-else @click="handleSave(scope.row)">
                      <SvgIcon name="save"></SvgIcon>
                    </li>
                    <li @click="handleDelete(scope.row, scope.$index)">
                      <SvgIcon name="delete"></SvgIcon>
                    </li>
                  </span>
                </template>
              </el-table-column>
            </el-table>
          </el-form>
        </div>
      </div>
      <div class="project-info-flow">
        <div class="project-header">
          <div class="project-header-icon"></div>
          <div class="project-header-title">变更记录</div>
        </div>
        <Dynamic
          :data="projectForm.tcProjectChangeRecordList"
          :projectMemberList="userList"
          :projectTreeData="projectTreeData"></Dynamic>
      </div>
    </div>
  </div>
</template>
<script setup>
import { useDictionary } from '@/use/use-dictionary'
import { ElMessage, ElMessageBox } from 'element-plus'
import { flatten, arrayToTree, treeFind } from '@/utils/task-utils'
import { getUserList } from '@/assets/api/user'
import dayjs from 'dayjs'
import Dynamic from '@/views/task/components/Dynamic'
import {
  getProjectInfo,
  saveProjectInfo,
  addProjectTaskItem,
  editProjectTaskItem,
  deleteProjectTaskItem,
  tcTaskProjectFiled,
} from '@/assets/api/project-info'
import { getTcTaskProjectParentList, deleteProject } from '@/assets/api/project'
import useProject from '@/store/project'
import { getDeptTree } from '@/assets/api/dept'

const projectStore = useProject()
const dict = useDictionary(['task_project_type', 'task_project_class', 'task_edit_mode'])
const emit = defineEmits(['refresh'])
const props = defineProps({
  projectId: {
    type: String,
    default: '',
  },
})

const projectStatus = ref(1)
const projectNoFinishLimit = ref(true)
watchEffect(() => {
  let projectInfo = projectStore.getProjectInfo
  projectStatus.value = projectInfo.projectStatus
  projectNoFinishLimit.value = projectInfo.projectStatus !== 2
})

const isEdit = ref(false)
const formRef = ref()
const projectForm = ref({
  projectGroup: {},
  user: {},
  dept: {},
})
const defaultProjectForm = ref({})
// 获取项目集
const projectTreeData = ref([])
const treeProps = reactive({
  children: 'children',
  label: 'projectName',
  value: 'projectId',
})
const deptProps = reactive({
  children: 'children',
  label: 'label',
  value: 'id',
})
const formRules = reactive({
  projectName: [{ required: true, message: '项目名称不可为空', trigger: 'blur' }],
  projectManager: [{ required: true, message: '项目经理不可为空', trigger: 'change' }],
  projectType: [{ required: true, message: '项目类型不可为空', trigger: 'change' }],
  projectClass: [{ required: true, message: '项目分类不可为空', trigger: 'change' }],
  deptId: [{ required: true, message: '归属部门不可为空', trigger: 'change' }],
  planEnd: [{ required: true, message: '计划时间不可为空', trigger: 'change' }],
  isCreate: [{ required: true, message: '任务编辑模式不可为空', trigger: 'change' }],
  // parentId: [{ required: true, message: '项目集不可为空', trigger: 'change' }],
})

const tableFormRef = ref()
const tableFormRules = reactive({
  itemName: [{ required: true, message: '请输入', trigger: 'blur' }],
  itemBegin: [{ required: true, message: '开始时间不可为空', trigger: 'change' }],
  itemEnd: [{ required: true, message: '结束时间不可为空', trigger: 'change' }],
})

const editModeList = [
  {
    label: '项目经理',
    value: 1,
  },
  {
    label: '项目经理/阶段负责人',
    value: 2,
  },
  {
    label: '全项目成员',
    value: 3,
  },
]

const editor = ref(null)
const projectRemark = ref('')
const newDragIndex = ref(-1)
const dragIndex = ref(-1)
const currentStage = ref(-1)
const defaultTime = reactive([new Date(0, 0, 0, 0, 0, 0), new Date(0, 0, 0, 23, 59, 59)])

onUpdated(() => {
  nextTick(() => {
    // const dragBox = document.querySelectorAll('.elTable .isDragBox')
    // dragBox.forEach((i, idx) => {
    //   i.setAttribute('draggable', 'true')
    //   i.ondragstart = () => dragStartItem(idx)
    //   i.ondragover = () => dragOverItem(idx)
    //   i.ondragend = () => dragEndItem()
    // })
  })
})
function dragStartItem(idx) {
  dragIndex.value = idx
}
const position = ref('')
function dragOverItem(index) {
  newDragIndex.value = index
  if (document.getElementsByClassName(`table-data-${index}`)[0]) {
    // 判断拖拽元素（鼠标指针位置判断） 在目标元素的Y轴位置
    const dragEL = event.offsetY
    // 获取目标元素高度
    const targetELHeight = document.getElementsByClassName(`table-data-${index}`)[0].scrollHeight
    // 将目标分成三份 （目标上 0、目标内 1、目标下 2）
    const targetPosition = targetELHeight / 3
    // 目标元素属性
    const dragELClass = document.getElementsByClassName(`active-drag`)[0]
    if (dragELClass) {
      clearELId()
      switch (Math.floor(dragEL / targetPosition)) {
        case 0:
          position.value = 'up'
          dragELClass.id = 'active-drag-up'
          return
        case 1:
          position.value = 'inner'
          dragELClass.id = 'active-drag-inner'
          return
        case 2:
          position.value = 'down'
          dragELClass.id = 'active-drag-down'
          return
      }
    }
  }
}

const infoForm = reactive({
  projectGroup: {},
  user: {},
  dept: {},
})
function getParentList() {
  getTcTaskProjectParentList().then((res) => {
    if (res.code === 200) {
      projectTreeData.value = res.rows || []
      infoForm.projectGroup = treeFind({ children: projectTreeData.value }, projectForm.value.parentId, 'projectId')
    } else {
      ElMessage.error(res.msg)
    }
  })
}

const deptList = ref([])
function getDeptTreeData() {
  getDeptTree().then((res) => {
    if (res.code === 200) {
      deptList.value = res.data || []
      infoForm.dept = treeFind({ children: deptList.value }, projectForm.value.deptId, 'id')
    } else {
      ElMessage.error(res.msg)
    }
  })
}

const userList = ref([])
function getUserListData() {
  getUserList().then((res) => {
    if (res.code === 200) {
      userList.value = res.rows || []
      infoForm.user = userList.value.find((item) => item.userId === projectForm.value.projectManager)
    } else {
      ElMessage.error(res.msg)
    }
  })
}

function clearELId() {
  // 清除所有id
  const tableELDatas = document.getElementsByClassName('isDragBox')
  for (let i = 0; i < tableELDatas.length; i++) {
    tableELDatas[i].id = ''
  }
}
//  日期限制
function itemBeginDisabled(time, row) {
  return time.getTime() > new Date(row.itemEnd).getTime()
}
function itemEndDisabled(time, row) {
  return time.getTime() < new Date(row.itemBegin).getTime()
}
function dragEndItem() {
  // 将数据扁平化
  const flatData = flatten(projectForm.value.tcTaskItemsList, 'itemsChildren')
  const data = flatData[dragIndex.value]
  const parentData = flatData[newDragIndex.value]
  // 判断拖拽元素是否为目标元素的父元素
  if (!(data.itemId === parentData.parentId || data.itemId === parentData.itemId)) {
    if (position.value === 'inner') {
      if (parentData.parentId !== 0) {
        // 限制只能在两级内拖动
      } else {
        data.parentId = parentData.itemId
      }
    } else {
      data.parentId = parentData.parentId
    }
  }
  if (position.value === 'down') {
    flatData.splice(dragIndex.value, 1)
    flatData.splice(newDragIndex.value + 1, 0, data)
  } else {
    flatData.splice(dragIndex.value, 1)
    flatData.splice(newDragIndex.value, 0, data)
  }
  // 扁平化数据重新转型后赋值
  const treeData = arrayToTree(flatData, 'itemId', 'parentId', 'itemsChildren')
  projectForm.value.tcTaskItemsList = treeData
  // 扁平化后重置id 避免样式影响
  clearELId()
  // 数据拖拽完成后 调用接口修改数据库数据
  editProjectTaskItem(data)
}
function activeClass({ row, rowIndex }) {
  if (rowIndex === newDragIndex.value) {
    return `isDragBox active-drag table-data-${rowIndex}`
  }
  return `isDragBox table-data-${rowIndex}`
}
// 查询详情
getInfo()
function getInfo() {
  getProjectInfo(props.projectId).then((res) => {
    const data = res.data
    projectStore.setProjectInfo(res.data)
    data.planTime = [data.planBegin, data.planEnd]
    data.parentId = data.parentId === 0 ? (data.parentId = null) : data.parentId
    projectForm.value = data
    defaultProjectForm.value = JSON.parse(JSON.stringify(data))
    // projectForm.tcTaskItemsList
    projectForm.value.tagList = JSON.parse(data.projectTag) || []
    currentStage.value = findCurrentStage(data.currentStage)
    projectRemark.value = data.projectRemark || ''
    getParentList()
    getUserListData()
    getDeptTreeData()
  })
}

// 阶段列表
const groupList = computed(() => {
  let data = JSON.parse(JSON.stringify(projectForm.value.tcTaskItemsList))
  let res = data.reduce((result, i) => {
    if (i.itemsChildren.length) {
      result.push(
        ...i.itemsChildren.map((j) => {
          // 拼接父级阶段名称
          j.itemName = `${i.itemName}/${j.itemName || ''}`
          return j
        })
      )
    } else {
      result.push(i)
    }
    return result
  }, [])
  return res
})

function findCurrentStage(stage) {
  let arr = typeof stage === 'string' ? stage.split(',') : []
  let currentStage = stage
  if (arr.length > 1) currentStage = arr[arr.length - 1]
  let index = -1
  switch (currentStage) {
    case -1:
      index = 0
      break
    case 0:
      index = projectForm.value.tcTaskItemsList.length
      break
    default:
      projectForm.value.tcTaskItemsList.forEach((item, i) => {
        if (item.itemId === currentStage) {
          index = i + 1
        }
      })
  }
  return index
}

const formStyle = reactive({
  '--margin': '0px',
})

function editProjectInfo() {
  isEdit.value = true
  formStyle['--margin'] = '20px'
}
function cancelEdit() {
  projectForm.value = defaultProjectForm.value
  projectForm.value.tagList = JSON.parse(defaultProjectForm.value.projectTag) || []
  inputVisible.value = false
  isEdit.value = false
  formStyle['--margin'] = '0px'
}
const saveLoading = ref(false)
function submitFrom() {
  formRef.value.validate((valid) => {
    if (valid) {
      saveLoading.value = true
      inputVisible.value = false
      const remark = editor.value.getHtml()
      const data = JSON.parse(JSON.stringify(projectForm.value))
      data.parentId = data.parentId === '' ? 0 : data.parentId
      const formData = JSON.parse(JSON.stringify(data))
      formData.projectTag = JSON.stringify(projectForm.value.tagList)
      delete formData.tcTaskItemsList
      delete formData.tagList
      formData.projectRemark = remark
      saveProjectInfo(formData).then((res) => {
        if (res.code === 200) {
          ElMessage.success('保存成功')
          formStyle['--margin'] = '0px'
          isEdit.value = false
          getInfo()
        } else {
          ElMessage.error(res.msg)
        }
        saveLoading.value = false
      })
    }
  })
}
function projectFiled() {
  ElMessageBox.confirm(`确认归档【${projectForm.value.projectName}】吗?`, '归档', {
    cancelButtonText: '取消',
    confirmButtonText: '确认',
    type: 'warning',
  })
    .then(() => {
      saveLoading.value = true
      tcTaskProjectFiled(props.projectId).then((res) => {
        if (res.code === 200) {
          ElMessage.success('归档成功')
          getInfo()
        } else {
          ElMessage.error(res.msg)
        }
        saveLoading.value = false
      })
    })
    .catch(() => {})
}
const deleteLoading = ref(false)
function deleteProjectClick() {
  ElMessageBox.confirm(`确定要删除项目【${projectForm.value.projectName}】吗?`, '删除确认', {
    cancelButtonText: '取消',
    confirmButtonText: '确认',
    type: 'warning',
  })
    .then(() => {
      deleteLoading.value = true
      deleteProject(props.projectId).then((res) => {
        if (res.code === 200) {
          ElMessage.success('删除成功')
          emit('refresh')
        } else {
          ElMessage.error(res.msg)
        }
        deleteLoading.value = false
      })
    })
    .catch(() => {})
}
let savePending = ref(false)
function isSavePending(type) {
  if (type === 'add') {
    if (savePending.value) {
      ElMessage.warning('请先保存！')
      return true
    } else {
      savePending.value = true
      return false
    }
  } else if (type === 'remove') {
    savePending.value = false
  }
}

function handleAdd(data, node) {
  if (!isSavePending('add')) {
    projectForm.value.tcTaskItemsList.push({
      parentId: 0,
      editFlag: true,
      itemsChildren: [],
      projectId: props.projectId,
      delKey: projectForm.value.length,
    })
  }
}
function handleAddChildren(row) {
  if (!row.itemsChildren || row.itemsChildren.length === 0 || !row.itemsChildren.at(-1).editFlag) {
    if (!isSavePending('add')) {
      row.itemsChildren.push({
        parentId: row.itemId,
        editFlag: true,
        // itemsChildren: [],
        projectId: props.projectId,
        // parent: row,
      })
    }
  } else {
    ElMessage.warning('请先保存！')
  }
}
function handleEdit(row) {
  if (!isSavePending('add')) {
    row.editFlag = true
  }
}

function handleSave(row) {
  row.itemEnd = dayjs(row.itemEnd).hour(23).minute(59).second(59).format('YYYY-MM-DD HH:mm:ss')
  delete row.parent

  tableFormRef.value.validate(async (valid) => {
    if (valid) {
      const isAdd = !row.itemId
      const res = await (isAdd ? addProjectTaskItem : editProjectTaskItem)(row)
      if (res.code === 200) {
        ElMessage.success('提交成功')
        row.editFlag = false
        getInfo()
      } else {
        ElMessage.error(res.msg)
      }
      isSavePending('remove')
    }
  })
}

function findPosi(tree, targetId, path = '') {
  for (let i = 0; i < tree.length; i++) {
    const node = tree[i]
    if (node.itemId === targetId) {
      return path + i
    }
    if (node.itemsChildren && node.itemsChildren.length > 0) {
      const childPath = `${path}${i}.itemsChildren.`
      const result = findPosi(node.itemsChildren, targetId, childPath)
      if (result !== null) {
        return result
      }
    }
  }
  return null
}

function handleDelete(row, index) {
  if (Array.isArray(row.itemsChildren) && row.itemsChildren.length > 0) {
    ElMessage.error('请先删除子阶段')
    return
  }
  ElMessageBox.confirm('是否确认删除此阶段', '提示', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(() => {
      if (row.itemId) {
        deleteProjectTaskItem(row.itemId).then((res) => {
          if (res.code === 200) {
            ElMessage.success('删除成功')
            getInfo()
          } else {
            ElMessage.error(res.msg)
          }
        })
      } else {
        const flatData = flatten(projectForm.value.tcTaskItemsList, 'itemsChildren')
        flatData.splice(index, 1)
        projectForm.value.tcTaskItemsList = arrayToTree(flatData, 'itemId', 'parentId', 'itemsChildren')
      }
      isSavePending('remove')
    })
    .catch(() => {})
}

function planDateChange(date) {
  // projectForm.value.planBegin = date && date.length === 2 && date[0]
  // projectForm.value.planEnd = date && date.length === 2 && date[1]
  projectForm.value.planBegin = date && date.length > 0 ? dayjs(date[0]).valueOf() : ''
  projectForm.value.planEnd = date && date.length > 0 ? dayjs(date[1]).valueOf() : ''
}

// 项目标签
const inputVisible = ref(false)
const tagList = ref([])
const tagValue = ref('')

function showInput() {
  inputVisible.value = true
  // nextTick(() => {
  //   selectUserRef.value.focus()
  // })
}

function tagCancel() {
  inputVisible.value = false
  tagValue.value = ''
}
function tagConfirm() {
  if (tagValue.value && tagValue.value.trim()) {
    let form = {
      tagName: tagValue.value,
    }
    if (projectForm.value.tagList.some((item) => item.tagName === tagValue.value)) {
      ElMessage.warning('输入了重复的标签')
    } else {
      projectForm.value.tagList.push(form)
      inputVisible.value = false
      tagValue.value = ''
    }
  } else {
    inputVisible.value = false
    tagValue.value = ''
  }
}
function deleteTag(tag) {
  projectForm.value.tagList.splice(projectForm.value.tagList.indexOf(tag), 1)
}
</script>
<style lang="scss" scoped>
.project-info {
  :deep(.elp-table) {
    .table-ation {
      .cell {
        justify-content: center;
      }
    }
    .cell {
      border-left: none;
      height: 100%;
      @include use-flex(center, normal, row);
      span {
        cursor: pointer;
        @include use-flex(center, normal, row);
      }
      .elp-table__expand-icon > .elp-icon {
        width: 1.5em;
        height: 1.5em;
        background: url('~@/assets/image/project/close.png') no-repeat;
        background-size: 100% 100%;
      }
      .elp-table__expand-icon > .elp-icon svg {
        width: 0;
        height: 0;
      }
      /*有子节点 且已展开*/
      .elp-table__expand-icon--expanded > .elp-icon {
        width: 1.5em;
        height: 1.5em;
        background: url('~@/assets/image/project/open.png') no-repeat;
        background-size: 100% 100%;
      }
    }
    .elp-table__expand-icon--expanded,
    .elp-table__expand-icon {
      transform: rotate(0deg);
      width: 15px;
      height: 15px;
      line-height: 8px;
      margin-right: 10px;
    }
  }
  .elTable {
    li {
      @include use-flex(center);
      justify-content: center;
      cursor: pointer;
      list-style-type: none;
      &:hover {
        background-color: var(--elp-color-info-light-9);
      }
    }
  }
  .table-action {
    display: flex;
    justify-content: center;
    overflow: hidden;
    .svg-icon {
      margin: 0 5px;
    }
  }

  &-center {
    @include use-flex(normal, flex-start);
  }

  &-content {
    overflow: auto;
    height: calc(100vh - 87px);
    box-sizing: border-box;
    padding: 20px;
    width: 72%;
    border-right: 1px solid #dcdfe6;
    :deep(.elp-form-item__label) {
      color: #777c85 !important;
    }
    :deep(.elp-form-item) {
      // margin-bottom: 5px !important;
      margin-bottom: var(--margin) !important;
    }
    .form-value {
      font-size: 14px;
      color: #2e3033;
    }
  }
  &-stage {
    // width: 300px;
    // overflow-x: auto;
    // width: 300px;
    &-content {
      box-sizing: border-box;
      padding: 20px;
      overflow-x: auto;
      .step-description {
        color: #959ba6;
      }
      .step-item {
        height: 40px;
        @include use-flex(center, center);
        width: 40px;
        border-radius: 50%;
      }
      .step-item-start {
        background: #005fff;
      }
      .step-item-default {
        background: #fff;
        border: 2px solid #e5effc;
      }

      .step-item-active {
        background: #fff;
        border: 2px solid #005fff;
      }

      .step-title-default {
        color: #777c85;
      }
      .step-title-active {
        color: #2e3033;
      }
      :deep(.elp-step) {
        max-width: 200px !important;
        flex-shrink: 0;
        .elp-step__title {
          min-height: 30px;
          font-weight: 700;
        }
      }
    }
  }
  &-flow {
    box-sizing: border-box;
    padding: 20px;
    overflow: auto;
    height: calc(100vh - 87px);
    width: 28%;
  }
}
:deep(.isDragBox) {
  // cursor: move;
  position: relative;
}
:deep(.active-drag) {
  position: relative;
}
:deep(#active-drag-up::after) {
  content: '';
  position: absolute;
  top: -1px;
  left: 0;
  width: 100%;
  height: 2px;
  background-color: #4b79f3;
  z-index: 99;
}
:deep(#active-drag-down::after) {
  content: '';
  position: absolute;
  bottom: -1px;
  left: 0;
  width: 100%;
  height: 2px;
  background-color: #4b79f3;
  z-index: 99;
}
:deep(#active-drag-inner::after) {
  content: '';
  position: absolute;
  left: 0;
  width: 100%;
  height: 40px;
  background-color: transparent;
  border: 1px solid #4b79f3;
  z-index: 99;
}
:deep(.elp-empty) {
  padding: 0;
}
:deep(.elp-divider) {
  // margin: 0 !important;
}

.svg-icon {
  width: 20px !important;
  height: 20px !important;
}

.project-header {
  @include use-flex(center, flex-start);
  margin-bottom: 10px;
  &-icon {
    width: 3px;
    height: 16px;
    background: #005fff;
    border-radius: 1px;
    margin-right: 8px;
  }
  &-title {
    font-size: 16px;
    font-weight: 700;
    color: #2e3033;
    line-height: 24px;
  }
  &-button {
    margin-left: auto;
  }
}

.tag-input {
  width: 150px !important;
  margin-right: 10px;
}

:deep(.elp-tag) {
  margin-right: 6px;
}

.project-describe {
  width: 100%;
  background: #f9fafb;
  border-radius: 4px;
  min-height: 100px;
  padding: 10px 15px;
  box-sizing: border-box;
  // margin-left: 50px;
  margin-top: 12px;
}

.project-cancel {
  color: red;
}

.svg-icon-btn {
  width: 14px !important;
  height: 14px !important;
}

.mb-4 {
  margin-bottom: 4px;
}
</style>
